import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Terminal } from 'xterm';
import classnames from 'classnames';

export default function Xterm(props: any) {
  const { className, onInput, value, term: _term } = props;

  let term: Terminal | null = _term;
  const [isFocused, setIsFocused] = useState(false);

  const terminalClassName = useMemo(() => {
    return [className, 'ReactXTerm', isFocused ? 'ReactXTerm--foucused' : null];
  }, [isFocused, className]);

  const handleInput = (data: any) => {
    term?.write(data);
    onInput && onInput(data);
  };
  const ref = useRef<any>(null);

  useEffect(() => {
    term = new Terminal();
    term.options = { fontFamily: 'Consolas', fontSize: 12 };
    term.open(ref.current as HTMLElement);
    if (onInput) {
      term.onData(handleInput);
    }
    if (value) {
      term.write(value);
    }
  }, []);

  return <div ref={ref} className={classnames(terminalClassName)} />;
}
